<template>
  <el-card class="tradmark-container">
    <el-button type="primary" size="default" icon="Plus" @click="addTreadmark"
      >添加品牌</el-button
    >
    <el-table style="margin: 10px 0px" border :data="tradeMarkList">
      <el-table-column
        label="序号"
        width="80px"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column label="品牌名称" align="center">
        <!-- 作用域插槽 -->
        <template #="{ row }">
          <pre>{{ row.name }}</pre>
        </template>
      </el-table-column>
      <el-table-column label="品牌LOGO" width="230px" align="center">
        <template #="{ row }">
          <img :src="row.logo" alt="" style="width: 200px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作" align="center">
        <template #="{ row }">
          <el-button
            type="primary"
            icon="Edit"
            @click="updateTradeMark(row)"
            circle
          />
          <el-popconfirm
            title="确定要删除这条记录吗?"
            width="200"
            @confirm="confirmDelete(row.id)"
          >
            <template #reference>
              <el-button type="danger" icon="Delete" circle />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="limit"
      :page-sizes="[10, 20, 50]"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      v-model="dialogFormVisible"
      :title="ruleForm.id ? '修改品牌' : '新增品牌'"
      width="500"
    >
      <el-form
        label-width="auto"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
      >
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="logo" prop="logo">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9981/api/file/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="ruleForm.logo" :src="ruleForm.logo" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm(ruleFormRef)"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import {
  reqTradeMarkList,
  saveList,
  deleteTradeMark,
} from '@/api/product/treadmark'
import type { TradeMarkData } from '@/api/product/treadmark/types'
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadProps,
} from 'element-plus'
import { ref, onMounted, reactive, nextTick } from 'vue'
let pageNo = ref<number>(1)
let limit = ref<number>(10)
let total = ref<number>(0)
let tradeMarkList = ref<TradeMarkData[]>([])
let dialogFormVisible = ref(false)

async function refreshTable(pageNoParam = 1) {
  let { data } = await reqTradeMarkList(pageNoParam, limit.value)
  pageNo.value = data.pageNo
  limit.value = data.pageSize
  total.value = data.total
  tradeMarkList.value = data.list
}
onMounted(() => {
  refreshTable()
})
function handleCurrentChange(pageNoParam: number) {
  refreshTable(pageNoParam)
}
function handleSizeChange(limit: number) {
  refreshTable(pageNo.value)
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<TradeMarkData>({
  name: '',
  logo: '',
})
// 校验图片不能为空
const checkLogo = (rule: any, value: string, callback: any) => {
  console.log('checkLogo', value)
  if (value == '') {
    callback(new Error('图片不能为空'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules<TradeMarkData>>({
  name: [
    { required: true, message: '不能为空', trigger: 'blur' },
    {
      min: 3,
      max: 25,
      message: '长度范围是3到10个汉字',
      trigger: 'blur',
    },
  ],
  // 这种方式已经能校验 非值输入框的校验了
  logo: [{ required: true, validator: checkLogo }],
})
function addTreadmark() {
  // 重置表单内容
  Object.assign(ruleForm, { id: undefined, name: '', logo: '' })
  delete ruleForm['id']
  dialogFormVisible.value = true
  // 第一次打开 dialog 时，ruleFormRef 还未初始化，此时 ruleFormRef.value.clearValidate会报错
  // TS 的?语法，表示 ruleFormRef.value有值时，则调用后面的方法，否则不调用
  // 解决方式一
  // ruleFormRef.value?.clearValidate('name')
  // ruleFormRef.value?.clearValidate('logo')
  // 解决方式二
  // 获取更新后的 dom
  nextTick(() => {
    ruleFormRef.value?.clearValidate('name')
    ruleFormRef.value?.clearValidate('logo')
  })
}
function cancel() {
  dialogFormVisible.value = false
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log('beforeAvatarUpload', rawFile)
  // if (rawFile.type !== 'image/jpeg') {
  //   ElMessage.error('图片必须是JPG格式!')
  //   return false
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error('图片大小不能超过2MB!')
  //   return false
  // }
  return true
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.logo = response.data
  // 图片上传成功，清理对应表单的验证信息
  ruleFormRef.value?.clearValidate('logo')
}

const updateTradeMark = async (row: TradeMarkData) => {
  // 清空表单校验内容
  nextTick(() => {
    ruleFormRef.value?.clearValidate('name')
    ruleFormRef.value?.clearValidate('logo')
  })
  dialogFormVisible.value = true
  // 更新表单内容
  Object.assign(ruleForm, row)
}

const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let resposne = await saveList(ruleForm)
      if (resposne.code === 200) {
        ElMessage.success(ruleForm.id ? '修改品牌成功' : '添加品牌成功')
      } else {
        ElMessage.error(ruleForm.id ? '修改品牌失败' : '添加品牌失败')
      }
      dialogFormVisible.value = false
      // 更新页面数据
      refreshTable(ruleForm.id ? pageNo.value : 1)
    }
  })
}

const confirmDelete = async (id: number) => {
  let resposne = await deleteTradeMark(id)
  if (resposne.code === 200) {
    ElMessage.success('删除品牌成功')
  } else {
    ElMessage.error('删除品牌失败')
  }
  // 刷新页面数据：可能删除的是当前页面最后一条数据
  // 如果是最后一条数据，则查询上一页的数据
  refreshTable(
    tradeMarkList.value.length > 1
      ? pageNo.value
      : Math.max(pageNo.value - 1, 1)
  )
}
</script>

<script lang="ts">
export default {
  name: 'TradeMark',
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
